<script lang="ts" setup>
  import { useRouter } from 'vue-router';
  import dayjs from 'dayjs';
  import { Message, Modal } from '@arco-design/web-vue';
  import { onMounted, ref } from 'vue';
  import useTable from '@/hooks/table';
  import { Game } from '@/types/game';
  import { deleteGame, getGameList } from '@/api/game';
  import GameCard from '@/components/game-card/index.vue';
  import ProvinceJSON from '@/config/province.json';
  import CityJSON from '@/config/city.json';
  import StageGameEditor from '@/views/game/components/stage-game-editor.vue';

  const props = defineProps<{
    gameInfo: Game;
  }>();

  const router = useRouter();

  const { pager, loading, total, list } = useTable<Game>();

  const getData = async () => {
    loading.value = true;
    try {
      const res = await getGameList({
        ...pager.value,
        parentId: props.gameInfo.id,
        approveStates: [1],
      });
      total.value = res?.data?.data?.total || 0;
      list.value = res?.data?.data?.list || [];
    } finally {
      loading.value = false;
    }
  };

  const handlePageIndexChanged = (pageIndex: number) => {
    pager.value.pageIndex = pageIndex;
    getData();
  };

  onMounted(() => {
    getData();
  });

  const stageGameEditorConfig = ref<{ visible: boolean; game?: Game }>({
    visible: false,
  });

  const handleStageGameDone = (refresh: boolean) => {
    if (refresh) {
      getData();
    }
    stageGameEditorConfig.value = {
      visible: false,
    };
  };

  const handleMenuClicked = async (game: Game, action: string) => {
    switch (action) {
      case 'DETAIL': {
        const routeInfo = router.resolve({
          name: 'GameDetailApp',
          query: {
            id: game.id,
          },
        });
        window.open(routeInfo.href);
        break;
      }
      case 'SCORE': {
        window.open(`https://www.qmx-golf.com/game/score?gameId=${game.id}`);
        break;
      }
      case 'SCORE_DETAIL': {
        window.open(
          `https://www.qmx-golf.com/game/score-detail?gameId=${game.id}`
        );
        break;
      }
      case 'EDIT': {
        router.push({
          name: 'GameEditorApp',
          query: {
            id: game.id,
            gameType:
              // eslint-disable-next-line no-nested-ternary
              game.childGameCount === 2
                ? 'stage'
                : game.gameType === 1
                ? 'parent'
                : 'normal',
          },
        });
        break;
      }
      case 'DELETE': {
        Modal.confirm({
          title: '确定删除该赛事？',
          content: '删除后无法恢复',
          onOk: async () => {
            await deleteGame(game.id);
            Message.success('已删除');
            getData();
          },
        });
        break;
      }
      default: {
        break;
      }
    }
  };
</script>

<template>
  <div>
    <a-row :gutter="[20, 20]">
      <a-col v-if="gameInfo.gameType === 1 && gameInfo.childGameCount === 2">
        <a-button @click="stageGameEditorConfig = { visible: true }"
          >添加比赛阶段</a-button
        >
      </a-col>
      <a-col>
        <a-table
          :bordered="{ cell: true }"
          :data="list"
          :loading="loading"
          :pagination="{
            total,
            current: pager.pageIndex,
            pageSize: pager.pageSize,
            showTotal: true,
            showJumper: true,
          }"
          @page-change="handlePageIndexChanged"
        >
          <template #columns>
            <template
              v-if="gameInfo.gameType === 1 && gameInfo.childGameCount === 2"
            >
              <a-table-column title="阶段" data-index="name"> </a-table-column>
              <a-table-column title="比赛时间" data-index="startDate">
                <template #cell="{ record }">
                  {{ dayjs(record.startDate).format('YYYY-MM-DD HH:mm:ss') }}
                  至
                  {{ dayjs(record.startDate).format('YYYY-MM-DD HH:mm:ss') }}
                </template>
              </a-table-column>
            </template>
            <template v-else>
              <a-table-column title="赛事" data-index="name">
                <template #cell="{ record }">
                  <GameCard :game-info="record" />
                </template>
              </a-table-column>
              <a-table-column title="球场">
                <template #cell="{ record }">
                  {{ record?.course?.name }}
                </template>
              </a-table-column>
              <a-table-column title="地区" data-index="phone">
                <template #cell="{ record }">
                  <span v-if="record.gameType === 0 || record.gameType === 2">
                    {{
                      ProvinceJSON.find((i) => i.id === record.province)?.name
                    }}/{{
                      CityJSON[record.province as keyof typeof CityJSON].find(
                        (i) => i.id === record.city
                      )?.name
                    }}
                  </span>
                  <span v-else>-</span>
                </template>
              </a-table-column>
              <a-table-column
                title="创建时间"
                data-index="gmtCreate"
                :width="180"
              >
                <template #cell="{ record }">
                  {{ dayjs(record.gmtCreate).format('YYYY/MM/DD HH:mm:ss') }}
                </template>
              </a-table-column>
            </template>
            <a-table-column
              title="操作"
              align="center"
              :width="80"
              fixed="right"
            >
              <template #cell="{ record }">
                <a-dropdown
                  @select="handleMenuClicked(record, $event as string)"
                >
                  <a-link> 操作 </a-link>
                  <template #content>
                    <a-doption value="DETAIL">查看详情</a-doption>
                    <a-doption value="SCORE_DETAIL">查看成绩</a-doption>
                    <a-doption value="EDIT"> 编辑 </a-doption>
                    <a-doption
                      :disabled="record.state !== -1 || record.createFrom === 2"
                      value="DELETE"
                    >
                      删除
                    </a-doption>
                  </template>
                </a-dropdown>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </a-col>
    </a-row>

    <StageGameEditor
      v-if="stageGameEditorConfig.visible"
      :stage-game="gameInfo"
      :game="stageGameEditorConfig.game"
      @close="handleStageGameDone"
    />
  </div>
</template>
